import type {
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
} from '@vben/types';

import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';

import { message } from 'ant-design-vue';

import { getAllTree } from '#/api';
import { BasicLayout, IFrameView } from '#/layouts';
import { $t } from '#/locales';
import type { GTableConfig } from '../utils/declar';

let componentMap = null;

// 获取 API 返回的菜单数据
interface MenuItem {
  id: number;
  name: string;
  component: string;
  path: string;
  meta: {
    config: string;
    icon: string;
    order: number;
    title: string;
  };
  parentId: number;
  children: MenuItem[] | null;
}

// 将树形结构的菜单数据转换为 Vue Router 格式
function transformMenuData(menuData: MenuItem[]) {
  return menuData.map(item => {
    const {meta} = item;
    console.log("meta",meta)
    if(item.bindEntity!==null){
      meta.config = item.bindEntity;
    }
    const route = {
      name: item.name,
      path: item.path,
      component: getComponent(item.component),
      meta,
      children: item.children ? transformMenuData(item.children) : [],
    };
    route.meta.title = $t(route.meta.title)
    return route;
  });
}

// 根据组件名称来动态加载组件
function getComponent(component: string) {
  if (component === 'BasicLayout') {
    return BasicLayout;
  } else {
    return componentMap[".."+component];
  }
}

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
  const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');
  const {routes} = options;
  const menuData = await getAllTree({className:"com.gumo.entity.Menu"});
  componentMap = pageMap;
  const route = transformMenuData(menuData);
  const routesArray = [...routes, ...route.filter(r => !routes.some(existingRoute => existingRoute.path === r.path))];
  options.routes = routesArray;


  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
  };
    const data = await generateAccessible(preferences.app.accessMode, {
    ...options,
    fetchMenuListAsync: async () => {
      message.loading({
        content: `${$t('common.loadingMenu')}...`,
        duration: 1.5,
      });
      const menuData = await getAllTree();
      return menuData;
    },
    // 可以指定没有权限跳转403页面
    forbiddenComponent,
    // 如果 route.meta.menuVisibleWithForbidden = true
    layoutMap,
    pageMap,
  });
    return data;
}



export { generateAccess };
